
using ctsu.Security;
using ctsu.BaseForms;
namespace ctsu.Admin.Forms
{
	public class FormSecurity
	{
		public FormSecurity()
		{

		}

		public static Permission GetFormAccess(FormInfoBase fi, User usr)
		{
			if (fi.Department == -1)
				return Permission.ReadWrite;

			Role itemRole = GetItemRole(fi, usr);
			if (itemRole != null)
				return itemRole.Access;
			Role deptRole = GetDepartmentRole(fi, usr);
			if (deptRole != null)
				return deptRole.Access;
			Role adminRole = GetAdminRole(fi, usr);
			if (adminRole != null)
				return adminRole.Access;

			return Permission.AccessDenied;

		}

		private static Role GetItemRole(FormInfoBase fi, User usr)
		{
			Role role = null;
			foreach (Role r in usr.Roles)
			{
				if (r.Item == fi.ID)
				{
					role = r;
				}
			}
			return role;
		}

		private static Role GetDepartmentRole(FormInfoBase fi, User usr)
		{
			Role role = null;
			foreach (Role r in usr.Roles)
			{
				if (r.Hierarchy == Hierarchy.Department &&
					fi.Department == r.Item || fi.Department == 3)
				{
					role = r;
				}
			}
			return role;
		}

		private static Role GetAdminRole(FormInfoBase fi, User usr)
		{
			Role role = null;
			foreach (Role r in usr.Roles)
			{
				if (r.Hierarchy == Hierarchy.Administration)
				{
					role = r;
				}
			}
			return role;
		}
	}
}
